package com.hnevc.androiduiclassone8;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QQLoginActivity extends AppCompatActivity {


    EditText mEtNumber,mEtpassword;
    Button mBtnLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qqlogin);

        initView();
        initEvent();
    }

    private void initEvent() {
        mBtnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //1
                String number=mEtNumber.getText().toString();
                String password=mEtpassword.getText().toString();
                //2
                saveUserInfo(number, password);
                //3
            }
        });
    }

    private void saveUserInfo(String number, String password) {
        String data=number+":"+password;
        try {
            FileOutputStream fos = openFileOutput("data.txt",MODE_PRIVATE);
            fos.write(data.getBytes());
            fos.close();
            Toast.makeText(QQLoginActivity.this
                    ,"保存成功!"
                    , Toast.LENGTH_SHORT).show();
        } catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    private Map<String,String>getUserInfo(){
        try {
            FileInputStream fis = openFileInput("data.txt");
            byte[] bytes=new byte[fis.available()];
            fis.read(bytes);
            fis.close();
            String temp=new String(bytes);
            String[] strs =temp.split(":");

            Map<String,String>map =new HashMap<>();
            map.put("number",strs[0]);
            map.put("password",strs[1]);

            return map;
        }catch (FileNotFoundException e){
            return null;
        }catch (IOException e){
            return null;
        }
    }

    private void initView() {
        mEtNumber=findViewById(R.id.et_number);
        mEtpassword=findViewById(R.id.et_password);
        mBtnLogin=findViewById(R.id.btn_login);

        final Map<String, String> userInfo = getUserInfo();
        if(userInfo!=null){
            mEtNumber.setText(userInfo.get("number"));
            mEtpassword.setText(userInfo.get("password"));
        }
    }
}
